package com.imooc.reader.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.imooc.reader.mapper.EvaluationMapper;
import com.imooc.reader.mapper.MemberMapper;
import com.imooc.reader.entity.Evaluation;
import com.imooc.reader.entity.Member;
import com.imooc.reader.service.EvaluationService;
import com.imooc.reader.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
@Service
@Transactional(propagation = Propagation.NOT_SUPPORTED,readOnly = true)
public class EvaluationServiceImpl implements EvaluationService {

    @Autowired
    private EvaluationMapper evaluationMapper;

    @Autowired
    private MemberMapper memberMapper;

    /**
     * 按图书编号查询有效短评
     * @param id 图书编号
     * @return 评论列表
     */
    @Transactional
    @Override
    public List<Evaluation> findEvaluation(Long id) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("book_id",id);
        queryWrapper.eq("state","enable");// 有效评论
        queryWrapper.orderByDesc("create_time");// 降序排名
        List<Evaluation> list = evaluationMapper.selectList(queryWrapper);

        for(Evaluation evaluation :list){
            Member member = memberMapper.selectById(evaluation.getMemberId());
            evaluation.setMember(member);
        }
        return list;
    }

    //添加短评
    @Override
    public void insertComment(Long bookId, Long memberId, Integer score, String content) {
        Evaluation evaluation=new Evaluation();
        evaluation.setBookId(bookId);
        evaluation.setMemberId(memberId);
        evaluation.setScore(score);
        evaluation.setContent(content);
        evaluation.setCreateTime(new Date());
        evaluationMapper.insert(evaluation);
    }

    //更新点赞
    @Override
    public Evaluation updateEnjoy(Long evaluationId) {
        Evaluation evaluation = evaluationMapper.selectById(evaluationId);
        evaluation.setEnjoy(evaluation.getEnjoy()+1);
        evaluationMapper.updateById(evaluation);
        return evaluation;
    }
}
